package com.miuix1.lifecycle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        iniComponent();
        init1com();
    }

    private void init1com() {
        TimerLiveViewModel u = new ViewModelProvider(this).get(TimerLiveViewModel.class);

        u.getT().observe(this, integer -> {
            TextView tv = findViewById(R.id.tvTime);
            tv.setText("TIME:" + integer);
        });

        Button bt = findViewById(R.id.bt);
        bt.setOnClickListener(v -> {
            int i = u.getT().getValue().intValue();
            u.setT(new Integer(i+1));
            Log.e("Value 监听", u.getT().getValue() + "");
        });
    }

    private void iniComponent() {
        final TextView tvTime = findViewById(R.id.tvTime);
        //通过ViewModelProviders得到ViewModel，如果ViewModel不存在就创建一个新的，如果已经存在就直接返回已经存在的
        TimerViewModel timerViewModel = new ViewModelProvider(this).get(TimerViewModel.class);

        timerViewModel.setOnTimeChangeListener(second -> {
            //更新UI界面
            runOnUiThread(() -> tvTime.setText("TIME:" + second));
        });

        timerViewModel.startTiming();
    }
}